//
//  CollectionViewController.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/1/30.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import UIKit
import SnapKit
import RxCocoa
import RxSwift
import RxDataSources

/// 收藏页面
class CollectionViewController: ViewController, Refreshable, LeftBarButtonItemable, NullData {
    
    var vm = CollectionViewModel()
    
    
    var tableView: UITableView!
    var datasource: RxTableViewSectionedReloadDataSource<CollectionSection>!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        bindUI()
      
        tableView.mj_header.beginRefreshing()
        // Do any additional setup after loading the view.
    }

    
    func initUI() {
        
        title = "收藏"
        view.backgroundColor = UIColor.lsf_color16(0xF9F9F9)
        setLeftItem()
        
        tableView = UITableView.init(frame: CGRect.zero, style: .plain)
        tableView.backgroundColor = UIColor.lsf_color16(0xF9F9F9)
        
        tableView.register(CollectionCell.classForCoder(), forCellReuseIdentifier: "CollectionCell")
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (maker) in
            maker.edges.equalTo(safeAreaInsets())
        }
    }
    
    func bindUI() {
        datasource = RxTableViewSectionedReloadDataSource.init(configureCell: { (ds, tv, ip, item) -> UITableViewCell in
            let cell = tv.dequeueReusableCell(withIdentifier: "CollectionCell", for: ip) as! CollectionCell
            
            let title = item.paperTitle
            let likeCount = item.likeCount
            cell.set(title: title, likeCount: likeCount)
            return cell
        })
        tableView.rx.setDelegate(self).disposed(by: disposeBag)
      

        vm.vmDatas.asObservable().bind(to: tableView.rx.items(dataSource: datasource)).disposed(by: disposeBag)
        
        initRefreshHeader(tableView) {  [weak self] in
            self?.vm.requestCommand.onNext(true)
        }
        
        vm.autoSetRefreshStatus(header: tableView.mj_header, footer: nil).disposed(by: disposeBag)
        
        ///空数据处理
        vm.isNull.asObservable().subscribe(onNext: { [weak self] (isNull) in
            if isNull {
                let nilView = self?.nilView(text: "还没有收藏记录哟~")
                self?.tableView.backgroundView = nilView
            }
            else {
                self?.tableView.backgroundView = nil
            }
        }).disposed(by: disposeBag)
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


extension CollectionViewController: UITableViewDelegate {
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        guard let section = vm.vmDatas.value.first else { return }
        if indexPath.row < section.items.count {
            let item = section.items[indexPath.row]
            guard let id = item.paperId else { return }
            guard let title = item.paperTitle else { return }
            let paperVC = PaperViewController.startPaper(id, status: PaperStatus.likes, title: title)
            navigationController?.pushViewController(paperVC, animated: true)
        }
        
    }
    
 
}

